package com.hxzy.controller.admin;

import com.hxzy.common.enums.AckCode;
import com.hxzy.common.properties.CaptchaProperty;
import com.hxzy.common.util.SecurityContextUtil;
import com.hxzy.common.util.TokenUtil;
import com.hxzy.common.vo.resp.R;
import com.hxzy.controller.admin.vo.req.LoginReq;
import com.hxzy.controller.admin.vo.resp.AdminLoginResp;
import com.hxzy.service.EmployeeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Objects;

/**
 * 功能描述:后台登录
 *
 * @author tonneyyy
 */
@Api(tags = "管理后台-商家和管理登录")
@RestController
@RequestMapping(value = "/api")
public class AdminLoginController {

    @Autowired
    private CaptchaProperty captchaProperty;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 管理员表业务逻辑
     */
    @Autowired
    private EmployeeService employeeService;

    /**
     * 令牌工具类
     */
    @Autowired
    private TokenUtil tokenUtil;

    /**
     * 一个账户，只允许登录一次(额外的需求)
     * @param req
     * @return
     */
    @ApiOperation(value = "登录")
    @PostMapping(value = "/login")
    public R<Object> login(@RequestBody @Valid LoginReq req){
        String redisKey=this.captchaProperty.getRedisPrefix()+req.getUuid();
        Object redisValue = this.redisTemplate.opsForValue().get(redisKey);
        if(Objects.isNull(redisValue)){
            return R.build(AckCode.SMS_CODE_OVERTIME);
        }

        if(!req.getCode().equalsIgnoreCase(redisValue.toString())){
            return R.build(AckCode.SMS_CODE_WRONG);
        }
        //删除验证码
        this.redisTemplate.delete(redisKey);

        //查询数据库
        AdminLoginResp adminLoginResp=this.employeeService.login(req);

        //把adminLoginResp存到redis中，换取令牌,把令牌使用jwt再加密
        String jwtToken=this.tokenUtil.createJwt(adminLoginResp);

        return R.okHasData(jwtToken);
    }


    @ApiOperation(value = "获取用户信息")
    @GetMapping(value = "/user/info")
    public  R<AdminLoginResp> userInfo(){
        return R.okHasData(SecurityContextUtil.getAdminUser());
    }

    @ApiOperation(value = "登出")
    @PostMapping(value = "/logout")
    public R<Object> logout(){
        this.tokenUtil.removeAdminToken();
        return R.ok();
    }
}
